package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestParam;

import java.beans.PropertyEditorSupport;
import java.util.Date;

@Controller
public class InitBinderTestController {

    // 将时间戳字符串转换成Date类型
    public static class TimestampToDateEditor extends PropertyEditorSupport {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            long timestamp = Long.parseLong(text);
            Date date = new Date(timestamp);
            setValue(date);
        }

        @Override
        public String getAsText() {
            Date date = (Date) getValue();
            return String.valueOf(date.getTime());
        }
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new TimestampToDateEditor());
    }

    @GetMapping("/test-init-binder")
    public String testInitBinder(@RequestParam Date date) {
        System.out.println("date = " + date);
        return "index";
    }
}
